package com.sxygsj.baselibrary.network

import android.util.Log
import com.google.gson.Gson
import com.sxygsj.baselibrary.network.netException.DataResultException
import okhttp3.ResponseBody
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Converter
import java.io.IOException
import java.lang.reflect.Type

/**
 * @Author LD
 * @Time 2020/9/2 14:01
 * @Describe Gson响应器
 * @Modify
 */
internal class GsonResponseBodyConverter<T>(private val gson: Gson, private val type: Type) :
    Converter<ResponseBody, T> {
    @Throws(IOException::class)
    override fun convert(response: ResponseBody): T {

        return try {
            val str = response.string()
            // TODO: 2021/2/26 根据具体的项目字段来设置
            val rootJsonObject = JSONObject(str)
            val code = rootJsonObject.getString("code")
            val msg = rootJsonObject.getString("msg")
            //请求成功的编码
            if ("100" == code) {
                Log.i(TAG, "convert: 100这里返回")
                gson.fromJson(str, type)
            } else {
                //根据这个code来判断是哪种类型的错误，假如2001代表未登录
                Log.i(
                    TAG,
                    "convert: 返回码不是100，抛出错误"
                )
                throw DataResultException(
                    msg,
                    code.toInt()
                )
            }
        } catch (e: JSONException) {
            e.printStackTrace()
            // TODO: 2021/2/26 这个的code该怎么写
            Log.i(TAG, "convert: json跑出异常")
            throw DataResultException(
                e.message!!,
                e.hashCode()
            )
        }
    }

    companion object {
        private const val TAG = "ceshi"
    }

}